import {
  Button,
  Space,
  Table,
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Typography,
} from "antd";

import { useEffect, useState } from "react";
import services from "../services";
const { Search } = Input;
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};
const User = () => {
  // 定义一个表格
  const [form] = Form.useForm();
  let [data, setData] = useState([]);
  const [editingKey, setEditingKey] = useState("");
  const [arr , changearr] = useState('')

  const isEditing = (record) => record._id === editingKey;

  let getList = async () => {
    let res = await services.UserList();
    setData(res.list);
    changearr(res.list);
    // console.log(res.list);
  };
  useEffect(() => {
    getList();
  }, []);
  const edit = (record) => {
    form.setFieldsValue({
      age: "",
      height: "",
      weight: "",
      sex: "",
      birthday: "",
      ...record,
    });
    setEditingKey(record._id);
  };
  const cancel = () => {
    setEditingKey("");
  };
  const save = async (record) => {
    try {
      const { _id } = record;

      // console.log(_id);
      const row = await form.validateFields();
      // console.log(row);
      const res = await services.UpdateList({
        _id,
        height: row.height,
        weight: row.weight,
        age: row.age,
        sex: row.sex,
        birthday: row.birthday,
      });
      getList();
      // console.log(res);
      setEditingKey("");
    } catch (err) {
      console.log("更新失败:", err);
    }
  };

  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});

  const handleChange = (pagination, filters, sorter) => {
    // console.log("Various parameters", pagination, filters, sorter);
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };
  const clearFilters = () => {
    setFilteredInfo({});
  };
  const clearAll = () => {
    setFilteredInfo({});
    setSortedInfo({});
  };
  const setAgeSort = () => {
    setSortedInfo({
      order: "descend",
      columnKey: "age",
    });
  };
  const handleDelete = async (key) => {
    // console.log(key);
    const res = await services.delList({ id: key });
    // console.log(res);
    getList();
  };
  const columns = [
    {
      title: "Name",
      dataIndex: "user",
      key: "user",
      ellipsis: true,
      fixed: "left",
      editable: true,
    },
    {
      title: "Sex",
      dataIndex: "sex",
      key: "sex",
      fixed: "left",
      editable: true,
      filters: [
        {
          text: "男",
          value: "男",
        },
        {
          text: "女",
          value: "女",
        },
      ],
      filteredValue: filteredInfo.sex || null,
      onFilter: (value, record) => record.sex.includes(value),
      sorter: (a, b) => a.sex.length - b.sex.length,
      sortOrder: sortedInfo.columnKey === "sex" ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: "Age",
      dataIndex: "age",
      key: "age",
      sorter: (a, b) => a.age - b.age,
      sortOrder: sortedInfo.columnKey === "age" ? sortedInfo.order : null,
      ellipsis: true,
      editable: true,
    },
    {
      title: "Height",
      dataIndex: "height",
      key: "height",
      editable: true,
      filters: [
        {
          text: "160",
          value: "160",
        },
        {
          text: "165",
          value: "165",
        },
        ,
        {
          text: "170",
          value: "170",
        },
      ],
      filteredValue: filteredInfo.height || null,
      onFilter: (value, record) => record.height == value,
      sorter: (a, b) => a.height - b.height,
      sortOrder: sortedInfo.columnKey === "height" ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: "Weight",
      dataIndex: "weight",
      key: "weight",
      editable: true,
      filters: [
        {
          text: "90",
          value: "90",
        },
        {
          text: "100",
          value: "100",
        },
        {
          text: "110",
          value: "110",
        },
      ],
      filteredValue: filteredInfo.weight || null,
      onFilter: (value, record) => record.weight == value,
      sorter: (a, b) => a.weight - b.weight,
      sortOrder: sortedInfo.columnKey === "weight" ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: "Birthday",
      dataIndex: "birthday",
      key: "birthday",
      editable: true,
      sorter: (a, b) => a.birthday.length - b.birthday.length,
      sortOrder: sortedInfo.columnKey === "birthday" ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: "Action1",
      dataIndex: "",
      //   key: "u",
      fixed: "right",
      width: 120,
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record)}
              style={{
                marginRight: 8,
              }}
            >
              Save
            </Typography.Link>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link
            disabled={editingKey !== ""}
            onClick={() => edit(record)}
          >
            Edit
          </Typography.Link>
        );
      },
    },
    {
      title: "Action2",
      dataIndex: "",
      fixed: "right",
      width: 120,
      render: (_, record) =>
        data.length >= 1 ? (
          <Popconfirm
            title="Sure to delete?"
            onConfirm={() => handleDelete(record._id)}
          >
            <a>Delete</a>
          </Popconfirm>
        ) : null,
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "age" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  const onSearch = (value) => {
      let res = arr.filter((item) => {return item.user.includes(value)})
      setData(res)
  }
  return (
    <>
      <Space
        style={{
          marginBottom: 16,
        }}
      >
        <Space direction="vertical">
          <Search
            placeholder="input search text"
            onSearch={onSearch}
            style={{
              width: 200,
            }}

            // onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
          />
        </Space>
        <Button onClick={setAgeSort}>Sort age</Button>
        <Button onClick={clearFilters}>Clear filters</Button>
        <Button onClick={clearAll}>Clear filters and sorters</Button>
      </Space>
      <Form form={form} component={false}>
        <Table
          columns={mergedColumns}
          dataSource={data}
          onChange={handleChange}
          pagination={{ pageSize: 5 }}
          scroll={{
            x: 1200,
          }}
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
        ></Table>
      </Form>
    </>
  );
};
export default User;
